package com.jiufen.Controller;

import com.jiufen.Pojo.Result;
import com.jiufen.Utils.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Value("${custom.file_path}")
    private  String FILEPATH ;

    @Autowired
    private UploadUtils uploadUtils;

    @Autowired
    private  MultipartFileToFileConverterUtils fileConverterUtils;

    @PostMapping("/upload")
    public Result upload2(MultipartFile file) throws IOException {
//        1.接收文件 名称要和前端传的一致 不一致则使用 @RequestParam("*")  进行 接收
        log.debug("--------------本次调用COS云端存储-----------------");
        log.info("接收参数：{}",file);
        //2.保存文件
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        log.info("文件名获取结果:{}", originalFilename);
        //需要将file 转换成 File
        File tempFile = fileConverterUtils.handleFileUpload(file);
        String url = uploadUtils.UploadUtils(tempFile, originalFilename);
        log.info("文件上传成功，返回结果：{}",url);
        return Result.success(url);
    }

    /**
     * 本地磁盘存储方式(暂不启用 备用方案)
     * @param name
     * @param age
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadLocal")
    public Result upload(@RequestParam(value = "username") String name, Integer age, MultipartFile file) throws IOException {
        //1.接收文件 名称要和前端传的一致 不一致则使用 @RequestParam("*")  进行 接收
        log.info("接收参数：{},{},{}",name,age,file);

        //2.保存文件
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        log.info("文件名获取结果:{}", originalFilename);

        //保存文件
            //获取文件后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uid = UUID.randomUUID().toString();
          //新的文件名称
        String newFileName = uid + extension;
        String fileName = FILEPATH + newFileName;
        log.info("文件保存名称及路径：{}",fileName);

        //保存文件
        file.transferTo(new File(fileName));
        return Result.success();
    }
}
